<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="专栏介绍：《让天下没有难学的Netty》系列，基于 Netty，以源码分析为主要手段，关键流程给出流程图，从 通道篇、内存篇、性能篇三个维度深度剖析 Netty 的实现原理。   1、通道概述我们从如下几个方面来简单了解一下 Channel。  通道的当前状态，open(端口打开)、connect(连接)。 通道的配置，包含通道的配置属性与网络通信选项(ChannelOption)。 IO 通道">
<meta property="og:type" content="article">
<meta property="og:title" content="Netty4 ChannelHandler 概述">
<meta property="og:url" content="https://www.codingw.net/posts/eab70bff.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="专栏介绍：《让天下没有难学的Netty》系列，基于 Netty，以源码分析为主要手段，关键流程给出流程图，从 通道篇、内存篇、性能篇三个维度深度剖析 Netty 的实现原理。   1、通道概述我们从如下几个方面来简单了解一下 Channel。  通道的当前状态，open(端口打开)、connect(连接)。 通道的配置，包含通道的配置属性与网络通信选项(ChannelOption)。 IO 通道">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20201129210717360.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20201129210953154.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20201129211116360.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20201129212730624.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">
<meta property="article:published_time" content="2020-10-25T14:54:01.000Z">
<meta property="article:modified_time" content="2021-04-26T12:32:51.015Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20201129210717360.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/eab70bff.html"/>





  <title>Netty4 ChannelHandler 概述 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/eab70bff.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Netty4 ChannelHandler 概述</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-10-25T22:54:01+08:00">
                2020-10-25
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/netty4/" itemprop="url" rel="index">
                    <span itemprop="name">netty4</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/eab70bff.html" class="leancloud_visitors" data-flag-title="Netty4 ChannelHandler 概述">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><blockquote>
<p>专栏介绍：《让天下没有难学的Netty》系列，基于 Netty，以源码分析为主要手段，关键流程给出流程图，从 通道篇、内存篇、性能篇三个维度深度剖析 Netty 的实现原理。 </p>
</blockquote>
<h2 id="1、通道概述"><a href="#1、通道概述" class="headerlink" title="1、通道概述"></a>1、通道概述</h2><p>我们从如下几个方面来简单了解一下 Channel。</p>
<ul>
<li>通道的当前状态，open(端口打开)、connect(连接)。</li>
<li>通道的配置，包含通道的配置属性与网络通信选项(ChannelOption)。</li>
<li>IO 通道方法诸如 read、write、connect、bind 与管道(ChannelPipeline)。</li>
<li>所有 IO 操作在 Netty 中都是异步的，调用 IO 方法例如 write 方法后，并不是等 IO 操作实际完成后再返回，而是会立即返回一个凭证，IO 操作完成后会将结果写入凭证中，典型的 Future设计模式。</li>
<li>Channel 具有父子关系，由于所有的 SocketChannel（客户端发起TCP连接）都是由 ServerSocketChannel（服务端接收连接）接收客户端连接而创建的，故 SocketChannel 的 parent() 方法会返回对应的 ServerSocketChannel。</li>
<li>所有通道对象在使用完后，请务必调用通道的colse方法来释放资源。</li>
</ul>
<p>本节将从如下3个方面来重点介绍Channel。</p>
<ul>
<li>Channel 常用API</li>
<li>Channel 配置与选项</li>
<li>NIO相关的Channel继承图</li>
</ul>
<span id="more"></span>

<h2 id="2、Channel常用API"><a href="#2、Channel常用API" class="headerlink" title="2、Channel常用API"></a>2、Channel常用API</h2><p>Channel 类图结构如下：<br><img src="https://img-blog.csdnimg.cn/20201129210717360.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>核心API一览：</p>
<ul>
<li>EventLoop eventLoop()<br>返回该通道注册的事件轮询器。</li>
<li>Channel parent()<br>返回该通道的父通道，如果是ServerSocketChannel实例则返回null，SocketChannel实例则返回对应的ServerSocketChannel。</li>
<li>ChannelConfig config()<br>返回该通道的配置参数。</li>
<li>boolean isOpen()<br>端口是否处于open，通道默认一创建isOpen方法就会返回true，close方法被调用后该方法返回false。</li>
<li>boolean isRegistered()<br>是否已注册到EventLoop。</li>
<li>public boolean isActive()<br>通道是否处于激活。NioSocketChannel的实现是java.nio.channels.SocketChannel实例的isOpen()与isConnected()都返回true。NioServerSocketChannel的实现是ServerSocketChannel.socket().isBound()，如果绑定到端口中，意味着处于激活状态。</li>
<li>ChannelFuture closeFuture()<br>Future模式的应用，调用该方法的目的并不是关闭通道，而是预先创建一个凭证(Future)，等通道关闭时，会通知该Future，用户可以通过该Future注册事件。</li>
<li>ChannelFuture bind(SocketAddress localAddress)<br>Netty服务端绑定到本地端口，开始监听客户端的连接请求。该过程会触发事件链(ChannelPipeline)。该部分将在后续讲解服务端启动流程时再详细分析。</li>
<li>ChannelFuture connect(SocketAddress remoteAddress)<br>Netty客户端连接到服务端，该过程同样会触发一系列事件(ChannelPipeline)。该部分将在后续讲解客户端启动流程时再详细分析。</li>
<li>ChannelFuture disconnect()<br>断开连接，但不会释放资源，该通道还可以再通过connect重新与服务器建立连接。</li>
<li>ChannelFuture close()<br>关闭通道，回收资源，该通道的生命周期完全结束。</li>
<li>ChannelFuture deregister()<br>取消注册。</li>
<li>Channel read()<br>通道读，该方法并不是直接从读写缓存区读取文件，而是向NIO Selecor注册读事件（目前主要基于NIO）。当通道收到对端的数后，事件选择器会处理读事件，从而触发ChannelInboundHandler#channelRead 事件，然后继续触发ChannelInboundHandler#channelReadComplete(ChannelHandlerContext)事件。</li>
<li>ChannelFuture write(Object msg)<br>向通道写字节流，会触发响应的写事件链，该方法只是会将字节流写入到通道缓存区，并不会调用flush方法写入通道中。</li>
<li>Channel flush()<br>刷写所有挂起的消息（刷写到流中）。</li>
<li>ChannelFuture writeAndFlush(Object msg)<br>相当于调用write与flush方法。</li>
</ul>
<h2 id="3、Channel配置与选项"><a href="#3、Channel配置与选项" class="headerlink" title="3、Channel配置与选项"></a>3、Channel配置与选项</h2><h4 id="3-1-Channel配置"><a href="#3-1-Channel配置" class="headerlink" title="3.1 Channel配置"></a>3.1 Channel配置</h4><p>ChannelConfig 的类图如下：<br><img src="https://img-blog.csdnimg.cn/20201129210953154.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>核心配置如下：</p>
<ul>
<li>Map&lt;ChannelOption&lt;?&gt;, Object&gt; options：选项，在下文会重点介绍。</li>
<li>int connectTimeoutMillis：连接超时时间。</li>
<li>int maxMessagesPerRead：每次读事件中调用读方法的最大次数(AbstractNioByteChannel)或读事件循环中最多处理的消息条数(AbstractNioMessageChannel)。</li>
<li>int writeSpinCount：一次写事件处理期间最多调用write方法的次数，引入该机制主要是为了避免一个网络通道写入大量数据，对其他网络通道的读写处理带来延迟，默认值为16。</li>
<li>ByteBufAllocator getAllocator()：返回该通道的内存分配器(ByteBuf)。<br>RecvByteBufAllocator getRecvByteBufAllocator()：读事件读缓冲区的分配策略。</li>
<li>boolean autoRead：是否自动触发read方法调用，默认为true，读事件触发后自动调用read方法 ，而无需应用程序显示调用。</li>
<li>int writeBufferHighWaterMark：设置写缓存区的高水位线。如果写缓存区中的数据超过该值，Channel#isWritable()方法将返回false。</li>
<li>int writeBufferLowWaterMark：设置写缓存区的低水位线。如果写缓存区的数据超过高水位线后，通道将变得不可写，等写缓存数据降低到低水位线后通道恢复可写状态(Channel#isWritable()将再次返回true)。<h4 id="3-2-ChannelOption"><a href="#3-2-ChannelOption" class="headerlink" title="3.2 ChannelOption"></a>3.2 ChannelOption</h4><img src="https://img-blog.csdnimg.cn/20201129211116360.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>网络通道(Channel)选项值，下面介绍一下与TCP协议相关的核心参数：</li>
<li>SO_BROADCAST<br>选择值类型:boolean。表值该数据包是否是广播包，true表示广播包，false表示非广播，如果包的IP地址为广播地址，但该选型为false，则在内核层会抛出错误。</li>
<li>SO_KEEPALIVE<br>对于面向连接的TCP socket,在实际应用中通常都要检测对端是否处于连接中,连接端口分两种情况:<ul>
<li><pre><code>连接正常关闭,调用close() shutdown()连接优雅关闭,send与recv立马返回错误,select返回SOCK_ERR
</code></pre>
</li>
<li><pre><code>连接的对端异常关闭,比如网络断掉,突然断电.
</code></pre>
</li>
</ul>
</li>
<li>SO_SNDBUF的大小<br>为了达到最大网络吞吐，socket send buffer size(SO_SNDBUF)不应该小于带宽和延迟的乘积。</li>
<li>SO_REUSEADDR<br>该参数如果设置为true的一个常用应用场景是端口复用(直接复用TIME_WAIT状态的socket)。</li>
<li>SO_LINGER<br>该参数是控制TCP关闭行为的。</li>
<li>SO_BACKLOG<br>服务端接受客户端连接的处理队列，在TCP三次握手协议中，服务端接收到客户端的SYN包后，会向客户端发送SYN+ACK包，同时会将连接放入到 backlog 队列中，等待客户端ACK包。在服务端没有接收到客户端的ACK包之前，连接会暂存 backlog 队列。</li>
<li>SO_TIMEOUT<br>以毫秒为单位定义套接字超时(SO_TIMEOUT)，它是等待数据的超时，或者换句话说，是两个连续数据包之间的最大活动周期。超时值为0将被解释为无限超时。如果没有设置该参数，读取操作将不会超时(无穷小超时)。个人思考：在NIO编程开发中应该不要设置该值，但为了保证每个连接的读平等，Netty会控制一次事件选择周期，最多可调用read方法的次数。</li>
<li>TCP_NODELAY<br>在TCP数据包发送的时候，有一种算法（Nagle算法）。该算法的核心是如果发生数据包比较小，为了提高带宽的利用率，会等待更多的数据到达后再发送或等待超时后将小包发送，也就是TCP发送延迟，TCP_NODELAY=true表示不使用tcp delay延迟，故禁用Nagle算法。通常接受端的ACK包也会使用延迟（默认40ms)，旨在合并多个ACK确认包。<br>Nagle 算法的改进在于：如果发送端欲多次发送包含少量字符的数据包(一般情况下,后面统一称长度小于MSS的数据包为小包,与此相对,称长度等于MSS的数据包为大包,为了某些对比说明,还有中包,即长度比小包长,但又不足一个MSS的包;MSS,TCP最大分段大小,以太网下一般就是1460字节。),则发送端会先将第一个小包发送出去,而将后面到达的少量字符数据都缓存起来而不立即发送,直到收到接收端对前一个数据包报文段的ACK确认、或当前字符属于紧急数据,或者积攒到了一定数量的数据(比如缓存的字符数据已经达到数据包报文段的最大长度)等多种情况才将其组成一个较大的数据包发送出去。</li>
</ul>
<h2 id="4、Channel-NIO-继承图"><a href="#4、Channel-NIO-继承图" class="headerlink" title="4、Channel NIO 继承图"></a>4、Channel NIO 继承图</h2><p>Channel 类继承图主要是想展示一下与 NIO 相关的 NioSocketChannel (客户端通道)与NioServerSocketChannel (服务端通道)在 Channel 中的位置。<br><img src="https://img-blog.csdnimg.cn/20201129212730624.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述"><br>Channel 通道统一抽象接口。</p>
<ul>
<li>AbstractChannel 通道默认抽象实现类</li>
<li>AbstractEpollChannel unix Epoll通道实现</li>
<li>AbstractOioChannel 阻塞IO通道抽象类</li>
<li>AbstractNioChannel NIO通道抽象类</li>
<li>AbstractNioByteChannel NIO客户端通道抽象类</li>
<li>AbstractNIoMessageChannel NIO服务端通道抽象类</li>
<li>NioSocketChannel  NIO客户端通道实现类</li>
<li>NioServerSocketChannel NIO服务端通道实现类</li>
</ul>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/b579d244.html" rel="next" title="初识 Kafka Producer 生产者">
                <i class="fa fa-chevron-left"></i> 初识 Kafka Producer 生产者
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/a79560fc.html" rel="prev" title="Netty4 Channel 概述">
                Netty4 Channel 概述 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81%E9%80%9A%E9%81%93%E6%A6%82%E8%BF%B0"><span class="nav-number">1.</span> <span class="nav-text">1、通道概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81Channel%E5%B8%B8%E7%94%A8API"><span class="nav-number">2.</span> <span class="nav-text">2、Channel常用API</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3%E3%80%81Channel%E9%85%8D%E7%BD%AE%E4%B8%8E%E9%80%89%E9%A1%B9"><span class="nav-number">3.</span> <span class="nav-text">3、Channel配置与选项</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1-Channel%E9%85%8D%E7%BD%AE"><span class="nav-number">3.0.1.</span> <span class="nav-text">3.1 Channel配置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-2-ChannelOption"><span class="nav-number">3.0.2.</span> <span class="nav-text">3.2 ChannelOption</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4%E3%80%81Channel-NIO-%E7%BB%A7%E6%89%BF%E5%9B%BE"><span class="nav-number">4.</span> <span class="nav-text">4、Channel NIO 继承图</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
